# -*- coding:utf-8 -*- 

"""
    @version: 1.0
    @author: Danson
    @software: PyCharm
    @file: el_hotel_by_url_pc_spider.py
    @time: 2017/7/25 16:15
    @description:根据艺龙 PC站的url获取酒店相关数据(通过页面获取酒店基本信息，接口获取房型数据)
    @todo:
"""
import requests
import scrapy
import signal
from scrapy.selector import Selector

import traceback
from scrapy.http import Request
from scrapy import signals
import os, sys
from pangolin.common.date_common import DateCommon
from pangolin.common.string_common import StringCommon
from pangolin.spider_enum.companyCodeEnum import getCompanyCode
from pangolin.common.db_operateCommon import *
from pangolin.items import HotelDetailItem
from pangolin.common.http_common import *
import logging
import re
from pangolin.settings import IS_SAVE_SERVER
from pangolin.settings import IS_SNAPSHOT
from datetime import *
import time as times

reload(sys)
sys.setdefaultencoding('UTF-8')


class ElHotelSpider(scrapy.Spider):
    name = 'el_hotel_by_url_pc_spider'
    allowed_domain = 'elong.com'

    def __init__(self, crawler, spider_name, city_code, company_code, task_id, task_date, timer_param,
                 timer_granularity, timer_id, url, lv_product_id, miss_product_flag):
        # 接受入参,全局引用
        self.save_server = IS_SAVE_SERVER
        self.snapshot = IS_SNAPSHOT

        self.spider_name = spider_name
        self.city_code = city_code
        self.company_code = company_code
        self.task_id = task_id
        self.task_date = task_date
        self.timer_param = timer_param
        self.timer_granularity = timer_granularity
        self.timer_id = timer_id
        self.url = url
        self.lv_product_id = lv_product_id
        self.miss_product_flag = miss_product_flag

        db_operate = DbOperateClass()
        urls = []
        lv_product_ids = {}
        if self.miss_product_flag == 'FALSE':
            sql = "SELECT yl_url,product_id FROM cpa_care_product WHERE city_code = '" + self.city_code + \
                  "' AND business_code='HOTEL'"
            try:
                (fc, count) = db_operate.select_by_sql(sql)
                for row in fc:
                    if row[0] is not None and row[0] != '':
                        url = row[0]
                        lv_product_id = row[1]
                        lv_product_ids.setdefault(url, lv_product_id)
                        urls.append(url)
                self.lv_product_ids = lv_product_ids
            except Exception as e:
                logging.info("Exception %s" % e)
                raise
            # 爬虫爬取前先删除同一批次同一城市的数据
            db_operate = DbOperateClass()
            db_operate.delete_pd_and_cd_data("hotel_pdetail", "hotel_cdetail", getCompanyCode(company_code),
                                             city_code, task_id, task_date)
        else:
            lv_product_ids.setdefault(self.url, self.lv_product_id)
            self.lv_product_ids = lv_product_ids
            urls.append(self.url)
        self.lv_product_ids = lv_product_ids
        self.start_urls = urls

        self.base_urls = "http://hotel.elong.com"
        # 绑定爬虫开始和结束信号，便于监听爬虫开始与结束
        self.crawler = crawler
        cs = crawler.signals
        cs.connect(self.spider_closed, signals.spider_closed)
        cs.connect(self.spider_opened, signals.spider_opened)

    def parse(self, response):
        sel = Selector(response)
        item = HotelDetailItem()
        try:
            item['type'] = "HOTEL"
            item['timer_param'] = self.timer_param
            item['timer_granularity'] = self.timer_granularity
            item['business_type'] = "hotel"

            item['product_table'] = "hotel_pdetail"
            item['data_type'] = "HotelDetail"
            item['detail_id'] = DateCommon.get_id_by_datetime()
            item['company_code'] = getCompanyCode(self.company_code)
            item['platform_code'] = "PC"  # 操作平台WAP，PC
            item['city_code'] = self.city_code
            hotel_name_tag = sel.xpath('//*[@class="t24 yahei"]').extract()[0]
            dr = re.compile(r'<[^>]+>', re.S)
            item['hotel_name'] = StringCommon.remove_blank(dr.sub('', hotel_name_tag))
            mode = re.compile(r'\d+')
            item['product_id'] = response.url.split("com/")[1].split("/")[0]
            item['come_date'] = DateCommon.get_current_date()
            item['leave_date'] = DateCommon.get_other_date(1)
            hotel_addr_tag = sel.xpath('//*[@class="mr5 left"]').extract()[0]
            item['hotel_addr'] = StringCommon.remove_blank(dr.sub('', hotel_addr_tag))
            score_tag = sel.xpath('//*[@id="txt1"]').xpath('@data-rate').extract()
            item['score'] = score_tag[0] if score_tag else ""
            image_num = sel.xpath('//*[@id="hotelDetailTabHandle"]/li[1]/text()').extract()[0]
            item['image_num'] = mode.findall(image_num)[0]
            item['introduction'] = ""
            item['score_tag'] = ""
            star_level_tag = sel.xpath('//*[@class="t24 yahei"]/b')
            if star_level_tag:
                item['star_level'] = star_level_tag.xpath('@title').extract()[0]  # 星级
            else:
                item['star_level'] = ""
            item['detail_url'] = response.url  # 详情页链接
            if self.snapshot == 'TRUE':
                item['snapshot_addr'] = " "
                # 获得截图地址
                # compress_path = self.save_screenshot(response, item['product_id'], self.city_code,
                #                                      self.company_code, self.task_id, self.task_date)
                # item['snapshot_addr'] = compress_path
            else:
                item['snapshot_addr'] = " "
            item['lv_product_id'] = self.lv_product_ids.get(response.url)
            item['create_time'] = DateCommon.get_current_date()
            item['update_time'] = item['create_time']
            item['task_id'] = self.task_id
            item['task_date'] = self.task_date

            # 商品详情
            item['commodity_table'] = "hotel_cdetail"
            item['room_type'] = []  # 房型
            item['commodity_id'] = []  # 商品id
            item['area'] = []  # 房间面积
            item['floor'] = []  # 楼层
            item['commodity_name'] = []  # 商品名称
            item['bed_type'] = []  # 床型
            item['broadband'] = []  # 宽带
            item['breakfast'] = []  # 早餐
            item['window'] = []  # 窗户
            item['increase_bed'] = []  # 加床
            item['people_num'] = []  # 入住人数
            item['commodity_url'] = []  # 商品预定链接
            item['cancel_rule'] = []  # 取消(退订)规则
            item['preferential'] = []  # 优惠
            item['sale_price'] = []  # 售价
            card_no = response.body.split('cardNo":')[1].split(',')[0]
            city_id = response.body.split('cityId":"')[1].split('",')[0]
            hotel_id = response.body.split('hotelIDs":"')[1].split('",')[0]
            room_type_url = "http://hotel.elong.com/ajax/detail/gethotelroomsetjva/?code=8928743&detailRequest.book" \
                            "ingChannel=1&detailRequest.cardNo={}&detailRequest.checkInDate={}&detailRequest.checkOut" \
                            "Date={}&detailRequest.cityId={}&detailRequest.customerLevel=11&detailRequest.hotelIDs={}" \
                            "&detailRequest.isAfterCouponPrice=true&detailRequest.isDebug=false&detailRequest.isLogin" \
                            "=false&detailRequest.isMobileOnly=false&detailRequest.isNeed5Discount=false&detail" \
                            "Request.isTrace=false&detailRequest.language=cn&detailRequest.needDataFromCache=true&" \
                            "detailRequest.orderFromID=50&detailRequest.payMethod=0&detailRequest.productType=0&" \
                            "detailRequest.promotionChannelCode=0000&detailRequest.proxyID=ZD&detailRequest.sell" \
                            "Channel=1&detailRequest.settlementType=0&detailRequest.updateOrder=false" \
                .format(card_no, item['come_date'], item['leave_date'], city_id, hotel_id)
            request = Request(room_type_url, meta={'item': item}, callback=self.parse_commodity,
                              errback=self.handel_erro)
            yield request

        except Exception as e:
            self.exception_handel(response, e)

    def parse_commodity(self, response):
        item = response.meta['item']
        room_data = json.loads(response.body)

        sel = Selector(text=room_data['value']['content'])
        room_tag = sel.css('.hdetail_type')
        i = -1
        if room_tag:
            item['lowest_price'] = room_data['value']['lowestProduct']['avgSalePrice']
            sites_evens = room_tag.css('.htype_list .htype_item')
            for site in sites_evens:
                room_type = site.css('.htype_info_name > span::text').extract()[0]
                comment = StringCommon.remove_blank(site.css('.htype_info_ty').extract()[0].replace("<span>", "")
                                                    .replace("</span>", "").replace("<p class=\"htype_info_ty\">", "")
                                                    .replace("</p>", "")) + "|"
                if comment.find('房间') > -1:
                    area = comment.split('房间')[0]
                else:
                    area = ""

                if comment.find('楼层') > -1:
                    floor = comment.split('楼层：')[1].split('\"')[0]
                else:
                    floor = ""

                if comment.find('无线') > -1 or comment.find('宽带') > -1:
                    broadband = comment.split('Desc()">')[1].split('|')[0]
                else:
                    broadband = ""

                if comment.find('床') > -1:
                    bed_type = comment.split('|')[1].split('|')[0]
                else:
                    bed_type = ""

                if comment.find('可住') > -1:
                    people_num_tag = comment.split('可住')[1].split('|')[0]
                else:
                    people_num_tag = ""

                window = ""
                people_num = people_num_tag.count("<i")
                sites_even = site.css('tbody tr[data-handle=rp]')
                for j, channel_site in enumerate(sites_even):
                    i = int(i) + 1
                    add_bed = room_data['value']['hotelTipInfo']['productsInfo'][i]['priceOfDays'][0]['addBed']
                    if add_bed is True:
                        add_bed_price = room_data['value']['hotelTipInfo']['productsInfo'][i]['priceOfDays'][0][
                            'addBedPrice']
                        increase_bed = "提供加床，加床价{}元。".format(add_bed_price)
                    else:
                        increase_bed = "不提供加床服务。"
                    commodity_name = channel_site.css('.ht_name > span::text').extract()[0]
                    breakfast = channel_site.css('.ht_brak::text').extract()[0]
                    cancel_rule_tag = channel_site.css('.ht_rule_free::text').extract()[0]
                    cancel_rule_desc = room_data['value']['hotelTipInfo']['productsInfo'][i]['cancelRuleDesc']
                    cancel_rule = cancel_rule_tag + "。" + cancel_rule_desc
                    # commodity_url_tag = channel_site.css('.tbl-same-type').xpath('@onclick').extract()[0]
                    # commodity_url = self.base_urls + commodity_url_tag.split("open('")[1].split("'")[0]
                    commodity_url = ""
                    data_rpid = channel_site.css('tr').xpath('@data-rpid').extract()[0]
                    data_sroomid = channel_site.css('tr').xpath('@data-sroomid').extract()[0]
                    data_rptype = channel_site.css('tr').xpath('@data-rptype').extract()[0]
                    commodity_id = str(item['product_id']) + str(data_rpid) + str(data_sroomid) + str(data_rptype)
                    preferential_tag = channel_site.css('.ht_retu > span')
                    if preferential_tag:
                        preferential = channel_site.css('.ht_retu > span::text').extract()[0]
                    else:
                        preferential = ""
                    sale_price = channel_site.css('.ht_pri_num::text').extract()[0]

                    item['room_type'].append(room_type)  # 商品类型或名称
                    item['commodity_id'].append(commodity_id)  # 商品id
                    item['area'].append(area)  # 房间面积
                    item['floor'].append(floor)  # 楼层
                    item['commodity_name'].append(commodity_name)  # 商品名称
                    item['bed_type'].append(bed_type)  # 床型
                    item['broadband'].append(broadband)  # 宽带
                    item['breakfast'].append(breakfast)  # 早餐
                    item['window'].append(window)  # 窗户
                    item['increase_bed'].append(increase_bed)  # 加床
                    item['people_num'].append(people_num)  # 入住人数
                    item['commodity_url'].append(commodity_url)  # 商品预定链接
                    item['cancel_rule'].append(cancel_rule)  # 取消(退订)规则
                    item['preferential'].append(preferential)  # 优惠
                    item['sale_price'].append(sale_price)  # 售价
            yield item
        else:
            logging.info("%s ,%s" % (item['detail_url'], "很抱歉，该酒店在此期间无法预订，建议您修改日期试试吧"))

    def handel_erro(self):
        logging.error("Inside_handel_erro")

    def exception_handel(self, response, e):
        logging.error("记录日志：标签变动 %s ,%s" % (response.url, e))
        logging.info("页面源码：%s ,%s" % (response.url, response.body))
        logging.error("Exception: %s" % traceback.format_exc().replace("\"", "'"))
        db_operate = DbOperateClass()
        # 错误描述只截取前500个字符，剩下的用***代替
        error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
        if len(error_desc) > 500:
            error_desc = error_desc[:500] + '***'
        # 错误日志记入日志表
        sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
              % ("C", getCompanyCode(self.company_code), "酒店", response.url, self.task_date, "timer_code",
                 "error_code", error_desc, str(self.task_id), str(self.task_date))
        db_operate.update_by_sql(sql)
        if self.save_server == 'TRUE':
            http_common = HttpCommon()
            operate_log = {'type': 'LOG',
                           'log_type': "C",
                           'company_code': getCompanyCode(self.company_code),
                           'busi_type': "酒店",
                           'url': response.url,
                           'batch_num': self.task_date,
                           'timer_code': "timer_code",
                           'error_code': "error_code",
                           'error_desc': error_desc,
                           'task_id': str(self.task_id),
                           'task_date': str(self.task_date)}
            http_common.get_method(operate_log)

    @classmethod
    def from_crawler(cls, crawler, **kwargs):
        logging.info('inside_from_crawler: ')
        if kwargs['miss_product_flag'] == 'FALSE':
            kwargs['url'] = ''
            kwargs['lv_product_id'] = ''
        else:
            kwargs['timer_granularity'] = ''
            kwargs['timer_id'] = ''

        return cls(
            crawler,
            spider_name=kwargs['spider_name'],
            city_code=kwargs['city_code'],
            company_code=kwargs['company_code'],
            task_id=kwargs['task_id'],
            task_date=kwargs['task_date'],
            timer_param=kwargs['timer_param'],
            timer_granularity=kwargs['timer_granularity'],
            timer_id=kwargs['timer_id'],
            url=kwargs['url'],
            lv_product_id=kwargs['lv_product_id'],
            miss_product_flag=kwargs['miss_product_flag']
        )

    def spider_opened(self, spider):
        logging.info('Spider_opened_list: %s' % spider.name)
        # 爬虫设为启动状态2
        if self.miss_product_flag == 'FALSE':
            db_operate = DbOperateClass()
            db_operate.update_status(2, "PYTHON", self.timer_id)

    def spider_closed(self, spider, reason):
        logging.info('spider_closed_list: %s ,reason:%s' % (spider.name, reason))
        db_operate = DbOperateClass()
        if self.miss_product_flag == 'TRUE':  # 补录
            db_operate.update_miss_status(1, self.url, self.task_id)
        elif self.miss_product_flag == 'FALSE':
            sql = "SELECT timer.timer_status FROM cpa_timer timer WHERE timer.timer_type='PYTHON' AND timer.timer_id " \
                  "= '" + self.timer_id + "'"
            (fc, count) = db_operate.select_by_sql(sql)
            spider.logger.info('SELECT_COUNT: %s ,SQL:%s' % (count, sql))
            timer_status = ""
            for row in fc:
                timer_status = row[0]
            logging.info("timer_status:%s" % timer_status)
            if timer_status == '2':
                db_operate.update_status(5, "PYTHON", self.timer_id)
